﻿using MP_Game.Protos.V1;
using SqlSugar;

namespace MP_VerifyServer
{
    public class VerifyService : IVerifyService
    {
        private readonly ISqlSugarClient _db;
        public VerifyService(ISqlSugarClient db)
        {
            _db = db;
        }
        public LoginRsp Login(LoginReq req)
        {
            LoginRsp rsp = new LoginRsp();

            // 1. 参数校验
            if (string.IsNullOrEmpty(req.Acct) || string.IsNullOrEmpty(req.Pwd))
            {
                rsp.Success = false;
                rsp.ErrorMsg = "账号名或密码不能为空！";
                return rsp;
            }

            // 2. 查库判断账号存在性
            var user = _db.Queryable<Account>()
                .Where(u => u.Acct == req.Acct)
                .First();
            if (user == null)
            {
                rsp.Success = false;
                rsp.ErrorMsg = "账号不存在！";
                return rsp;
            }

            // 3. 账号存在，验证密码
            if (user.Pwd != req.Pwd)
            {
                rsp.Success = false;
                rsp.ErrorMsg = "密码错误！";
                return rsp;
            }

            rsp.Success = true;
            rsp.AccessToken = "tokentoken";
            return rsp;
        }

        public RegistRsp Regist(RegistReq req)
        {
            RegistRsp rsp = new RegistRsp();

            // 1. 参数校验
            if (string.IsNullOrEmpty(req.Acct) || string.IsNullOrEmpty(req.Pwd))
            {
                rsp.Success = false;
                rsp.ErrorMsg = "账号名或密码不能为空！";
                return rsp;
            }

            // 2. 查库判断账号存在性
            var user = _db.Queryable<Account>()
                .Where(u => u.Acct == req.Acct)
                .First();
            if (user != null)
            {
                rsp.Success = false;
                rsp.ErrorMsg = "账号已存在！";
                return rsp;
            }

            // 3. 注册成功，写入数据库
            var newAccount = new Account
            {
                Acct = req.Acct,
                Pwd = req.Pwd,
                CreateDate = DateTime.Now,
            };
            long id = _db.Insertable(newAccount).ExecuteReturnBigIdentity();

            rsp.Success = true;
            rsp.AccessToken = "tokentoken";
            return rsp;
        }
    }
}
